package com.colter.project.sample.thread.part02.test1;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

//使用读写锁
public class Test5 {
	public static void main(String[] args) {
		PricesInfo pricesInfo = new PricesInfo();
		Reader[] readers = new Reader[5];
		Thread[] threadReaders = new Thread[5];
		for (int i = 0; i < readers.length; i++) {
			readers[i] = new Reader(pricesInfo);
			threadReaders[i] = new Thread(readers[i]);
		}
		
		Writer writer = new Writer(pricesInfo);
		Thread writerThread = new Thread(writer);
		
		for (int i = 0; i < threadReaders.length; i++) {
			threadReaders[i].start();
		}
		
		writerThread.start();
		
		
	}
}

class PricesInfo {
	private double price1;
	private double price2;
	private ReadWriteLock lock;

	public PricesInfo() {
		super();
		this.price1 = 1;
		this.price2 = 2;
		this.lock = new ReentrantReadWriteLock();
	}

	public double getPrice1() {
		lock.readLock().lock();
		double value = price1;
		lock.readLock().unlock();
		return value;
	}

	public double getPrice2() {
		lock.readLock().lock();
		double value = price2;
		lock.readLock().unlock();
		return value;
	}

	public void setPrice(double price1, double price2) {
		lock.writeLock().lock();
		this.price1 = price1;
		this.price2 = price2;
		System.out.println("lock  change price:" + price1 + " "+ price2);
		lock.writeLock().unlock();
	}
}

class Reader implements Runnable {
	private PricesInfo pricesInfo;

	public Reader(PricesInfo pricesInfo) {
		super();
		this.pricesInfo = pricesInfo;
	}

	@Override
	public void run() {
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for (int i = 0; i < 10; i++) {
			System.out.println("Price1:" + pricesInfo.getPrice1());
			System.out.println("Price2:" + pricesInfo.getPrice2());
		}
	}

}

class Writer implements Runnable {
	private PricesInfo pricesInfo;

	public Writer(PricesInfo pricesInfo) {
		super();
		this.pricesInfo = pricesInfo;
	}

	@Override
	public void run() {
		for (int i = 0; i < 3; i++) {
			System.out.println("change price start");
			pricesInfo.setPrice((int)(Math.random()*10), (int)(Math.random()*8));
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("change price end");
		}
	}

}
